// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// t [author] rhyme_lph
// r [email]  rhymelph@gmail.com
// s [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/transaction_entity.dart';
import 'package:finance_app/src/provider/dashboard/transaction/all_transactions_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/form_utils.dart';
import 'package:finance_app/src/utils/language_utils.dart';
import 'package:finance_app/src/utils/transaction_type_utils.dart';
import 'package:finance_app/src/widgets/button/filter_button.dart';
import 'package:finance_app/src/widgets/button/normal_down_button.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/chip/normal_chip.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_item.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_title_item.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "allTransactionsPage")
class AllSalesTransactionsPage extends StatefulWidget {
  final int type;
  final int contactId;
  final int accountId;
  final String initFilter;
  final String dueDate;

  const AllSalesTransactionsPage(
      {Key key,
      this.type,
      this.contactId,
      this.initFilter,
      this.accountId,
      this.dueDate})
      : super(key: key);

  @override
  _AllSalesTransactionsPageState createState() =>
      _AllSalesTransactionsPageState();
}

class _AllSalesTransactionsPageState extends State<AllSalesTransactionsPage>
    with PagePresenter<AllSalesTransactionsPage, AllTransactionsProvider> {
  @override
  void initState() {
    provider.type = widget.type;
    provider.initMenuList(widget.type);
    provider.contactId = widget.contactId;
    if (widget.initFilter != null) {
      if (widget.initFilter.contains(',')) {
        provider.currentSelectFilterList.addAll(widget.initFilter.split(','));
      } else {
        provider.currentSelectFilterList.add(widget.initFilter);
      }
    }
    if (widget.dueDate != null) {
      provider.dueDate = widget.dueDate;
    }
    super.initState();
  }

  @override
  PreferredSizeWidget get appBar =>
      getDefaultAppBar(title: provider.title, actions: [
        if (widget.type == 5 || widget.type == 2)
          NormalMorePopupButton(
            menuList: provider.menuList,
            onSelect: provider.onSelectMenu,
          )
      ]);

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: Column(
          children: [
            AppSpaces.h20,
            SearchInputField(
              controller: provider.searchController,
              focusNode: provider.searchFocusNode,
            ),
            AppSpaces.h20,
            buildTimeSoreAndFilter(),
            AppSpaces.h20,
            _buildFilterList(),
            Expanded(
                child: listBuilder<Tuple2<bool, List<TransactionEntity>>>(
              selector: (_, __) => Tuple2(
                  __.hasUp,
                  __.transactionList == null
                      ? null
                      : List.from(__.transactionList)),
              builder: (BuildContext context,
                      Tuple2<bool, List<TransactionEntity>> value,
                      Widget child) =>
                  SmartRefresher(
                controller: provider.refreshController,
                onRefresh: provider.onRefresh,
                onLoading: provider.onLoadMore,
                enablePullUp: value.item1,
                child: value.item2 == null
                    ? super.buildLoadingWidget
                    : value.item2.length == 0
                        ? super.buildEmptyWidget
                        : ListView(
                            children: _buildTransactionList(),
                          ),
              ),
            )),
          ],
        ),
      );

  Row buildTimeSoreAndFilter() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        _buildTimeSelect(),
        FilterButton(
          onPressed: provider.onShowFilter,
        ),
      ],
    );
  }

  Widget _buildFilterList() {
    return listBuilder<int>(
        builder: (BuildContext context, int value, Widget child) => value == 0
            ? Container()
            : Container(
                height: getDp(32),
                margin: EdgeInsets.only(
                  bottom: getDp(5),
                  top: getDp(5),
                ),
                alignment: Alignment.centerLeft,
                child: ListView.separated(
                  padding: EdgeInsets.symmetric(
                    horizontal: getDp(10),
                  ),
                  scrollDirection: Axis.horizontal,
                  shrinkWrap: true,
                  itemBuilder: (BuildContext context, int index) =>
                      value - 1 == index && provider.rangeTime != null
                          ? NormalChip(
                              title: provider.rangeTime,
                              onClose: provider.onClearRangeTime,
                            )
                          : _buildFilterItem(context, index),
                  itemCount: value,
                  separatorBuilder: (BuildContext context, int index) {
                    return Container(
                      width: getDp(15),
                    );
                  },
                ),
              ),
        selector: (_, __) => __.filterListLength);
  }

  Widget _buildTimeSelect() {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalDownButton(
              title: value,
              onTap: provider.onSelectTime,
            ),
        selector: (_, __) => __.currentSelectTime);
  }

  Widget _buildFilterItem(BuildContext context, int index) {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalChip(
              title: LanguageUtils.translateFilter(value),
              onClose: () => provider.onRemoveFilter(value),
            ),
        selector: (_, __) => __.currentSelectFilterList[index]);
  }

  List<Widget> _buildTransactionList() {
    List<Widget> child = [];
    for (final item in provider.transactionMap.entries) {
      child.add(TransactionRecordTitleItem(
        title: item.key,
      ));
      child.addAll(List.generate(
          item.value.length,
          (index) => listBuilder<TransactionEntity>(
                selector: (_, __) => item.value[index],
                builder:
                    (BuildContext context, TransactionEntity e, Widget child) {
                  return TransactionRecordItem(
                    onTap: () => provider.onNavTransactionDetail(e),
                    tag: TransactionTypeUtils.getTransactionType(
                        e.transactionType),
                    name: e.name ?? '',
                    currencyCode: e.currencyCode,
                    time: DateTimeUtils.formatDateTimeString(e.issuedAt),
                    amount: e.total?.toDouble(),
                    billNumber: e.number,
                    isUnpaid: e.status == 'open' && e.employeeId == null,
                    status: e.isOverdue == 1 && e.status == 'open'
                        ? 'Overdue'
                        : FormUtils.getStatus(
                            TransactionTypeUtils.getTransactionTypeStatus(
                                e.transactionType),
                            e.status,
                            e.status == 'open' && e.employeeId == null ? 1 : 0),
                  );
                },
              )));
    }
    return child;
  }
}
